<template>
    <div class="detail-download-area">
        <div class="game-introduce">
            <div class="introduce-title">
                <div class="introduce-logo" :style="`background-image: url(${$baseUrl+freeGiftList.icon});`"></div>
                <div class="introduce-info">
                    <div class="introduce-name">{{freeGiftList.title}}</div>
                    <p class="score">
                        <p :title="freeGiftList.desc">{{ freeGiftList.desc }}</p>
						<!-- <StarRating v-model="rating" :max-stars="5" />
                        <span class="average_score">{{freeGiftList.average_score || 9.9}}分推薦</span> -->
					</p>
                    <!-- <span class="count-text">3331.0万下载量</span> -->
                    <div class="download-game-category">
                        <div class="tag_list">
                            <span class="tag" v-for="(item,index) in freeGiftList.tag" v-show="lang == 'zh' ? index < 3 : index < 2" :key="index">{{item}}</span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- <div class="introduce-description"><span>{{freeGiftList.desc}}</span></div> -->
<!--            <a style="margin: initial;text-decoration: none;" @click="$router.push(url)" target="_blank">-->
<!--                <div class="introduce-ranking" style="cursor: pointer;">-->
<!--                    <div class="introduce-left">-->
<!--                        <img src="//static-gamecenter.biligame.net/images/introduce-ranking.2b116b67.svg" alt="">-->
<!--                        <div class="ranking-precedence">-->
<!--                            <span>{{$t('Hot_List')}} </span>-->
<!--                            <span> No.{{freeGiftList.hot_order}}</span>-->
<!--                        </div>-->
<!--                    </div>-->


<!--                    <div class="introduce-right">-->
<!--                        <p>{{$t('All_Hot_list')}}</p>-->
<!--                        <div class="introduce-right-logo">-->
<!--                            <img src=""-->
<!--                                alt="">-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->
<!--            </a>-->
        </div>
        <div class="game-download">
            <button v-if="freeGiftList.online" class="start-game" @click="open_game(freeGiftList.id,freeGiftList.title)">{{$t('play_game')}}</button>
            <button v-if="!freeGiftList.online" class="end-game end2">{{$t('soon_come_online')}}</button>
            <button v-if="isPwa && freeGiftList.online" class="start-game" id="down_game" @click="updatePwaConfig(freeGiftList.icon,freeGiftList.title,freeGiftList.id)" @mouseenter="charge_content" @mouseleave="charge_content" style="display:flex;min-width:83px;">
              {{$t('down_game')}}
            </button>
            <button class="end-game" v-if="!isPwa">已安裝</button>
        </div>
    </div>
</template>

<script setup>
import { reactive,ref,getCurrentInstance,nextTick } from 'vue'
import { useRouter } from 'vue-router'
import {useGetGameUrl} from '@/hooks/getGameUrl'
import { useUserInfoStore } from '@/store/modules/user_info/index';
import StarRating from "@/components/StarRating/index.vue"
import { useSetPwa } from '@/store/modules/setPwa/index';

const down_text = ref('');
const down_status = ref(false);
const rating = ref(9.3/2);
const user_infoStore = useUserInfoStore();
let user_info = reactive(user_infoStore.userInfo)
const router = useRouter()
const url = '/home/ranks'

let lang = ref('')
if(localStorage.getItem('lang') == 'en'){
    lang.value = 'en'
}else{
    lang.value = 'zh'
}


const props = defineProps(['freeGiftList'])
const freeGiftList = reactive(props.freeGiftList)
const open_game = async (game_id,game_name) => {
    const url = router.resolve({ path: '/playgame',query: { id: game_id,game_name: game_name } }).href;
    window.open(url)
}
const charge_content = () => {
  if (down_status.value === false){
    down_text.value = document.getElementById('down_game').innerHTML;
  }
  document.getElementById('down_game').innerHTML = '' +
      '<svg t="1731298806461" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5800" width="20" height="20"><path d="M849.124 704.896c-1.04 3.158-17.3 59.873-57.25 118.191-34.578 50.306-70.333 101.019-126.803 101.91-55.533 0.975-73.303-33.136-136.707-33.136-63.324 0-83.23 32.245-135.713 34.111-54.255 2.221-96.004-54.951-130.712-105.011-70.935-102.55-125.553-290.6-52.301-416.626 36.04-63.055 100.82-103.136 171.364-104.231 53.161-1.005 103.74 36.012 136.029 36.012 33.171 0 94.357-44.791 158.906-38.09 27.026 1.152 102.622 11.299 151.328 81.892-3.832 2.607-90.452 53.724-89.487 157.76 1.302 125.597 110.174 166.79 111.346 167.218M633.697 230.75c29.108-35.506 48.235-84.314 43.203-132.785-41.56 1.63-92.197 27.6-122.292 62.897-26.609 30.794-50.062 80.362-43.52 128.27 46.177 2.805 93.657-24.182 122.609-58.382" p-id="5801" fill="#ffffff"></path></svg>' +
      '<svg t="1731298647917" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4375" width="20" height="20"><path d="M181.248 862.208a136.533333 136.533333 0 0 1-14.336-68.266667V230.741333a136.533333 136.533333 0 0 1 14.336-68.266666L521.898667 512z m484.693333-201.728L318.122667 853.333333a186.026667 186.026667 0 0 1-92.501334 34.133334h-3.072l331.776-341.333334z m41.984-273.066667l73.386667 41.301334c27.306667 15.36 68.266667 43.008 68.266667 84.309333s-40.96 68.266667-68.266667 83.626667l-73.386667 41.301333L586.410667 512zM222.549333 136.533333h3.072a188.416 188.416 0 0 1 92.501334 34.133334l347.818666 193.877333L554.325333 477.866667 222.549333 136.533333z" fill="#ffffff" p-id="4376"></path></svg>';
//   console.log(down_status.value,123321);
//   console.log(down_text.value,123321);
  if (down_status.value){
    document.getElementById('down_game').innerHTML =down_text.value;
    down_status.value=false;
  }else{
    down_status.value=true;
  }
}

const updatePwaConfig = (icon,title,game_id) => {
    const iconSrc = `https://${window.location.hostname}/game/public${icon}`
    const url = `https://${window.location.hostname}/`+router.resolve({ path: '/playgame',query: { id: game_id,game_name: title } }).href;
// 动态更新 PWA 图标和名称
    let manifest = document.querySelector('link[rel="manifest"]');
    if (manifest) {
        // 如果存在 manifest 文件，修改其图标和名称
        fetch(manifest.href)
            .then(response => response.json())
            .then(data => {
                console.log(data);
                // 更新应用名称和图标
                data.name = title; // 更新名称
                data.short_name = title; // 更新短名称
                data.icons = [{src: iconSrc, sizes: "192x192", type: "image/png"}]; // 更新图标
                data.start_url = url
                // 重新生成 manifest 文件
                const updatedManifest = new Blob([JSON.stringify(data)], {type: 'application/json'});
                const updatedManifestUrl = URL.createObjectURL(updatedManifest);
                
                // 更新 manifest
                manifest.href = updatedManifestUrl;
                try {
                    pwaEvent.prompt()
                } catch (error) {
                    if(lang.value == 'zh'){
                        ElMessage.warning("该浏览器不支持安装到桌面，请手动添加到收藏夹")
                    }else{
                        ElMessage.warning("This browser does not support installation to the desktop, please add to the favorites manually")
                    }
                }
            });
    }
}


let pwaEvent = null
let setPwa_store = useSetPwa();
// 主线程中的 JavaScript
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(function(reg) {
    //   console.log('Service Worker Registered');

      // 获取当前的语言设置
      const lang = localStorage.getItem('lang');

      // 使用 postMessage 传递语言设置给 Service Worker
      if (reg.active) {
        reg.active.postMessage({ lang });
      }
    });

    pwaEvent = setPwa_store.getPwa()
    // console.log(pwaEvent,'pwaEvent');
    
}


let isPwa = ref(false)
const pwa2 = localStorage.getItem('isPwa')
if(pwa2 == 'true'){
    isPwa.value = true
    
}
window.addEventListener('beforeinstallprompt', (e) => {
    console.log(e);
    pwaEvent = e
    isPwa.value = true
    localStorage.setItem('isPwa',true)
    setPwa_store.setPwa(e)
})

window.addEventListener('appinstalled', () => {
    console.log('应用已安装!');
    isPwa.value = false
    localStorage.setItem('isPwa',false)
    const url = router.resolve({ path: '/playgame',query: { id: freeGiftList.id,game_name: freeGiftList.title } }).href;
    window.location.href = url
});

</script>

<style lang="less" scoped>
.detail-download-area {
    margin-left: 20px;
    padding: 16px;
    //width: 396px;
    //flex: 0.8;
    // height: 140px;
    background-color: rgb(255 255 255 / 50%);
    border-radius: 10px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, .1);

    .game-introduce {
        margin-top: 5px;
        .introduce-ranking:hover {
            background: #ffedc8;
        }

        .introduce-ranking {
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-pack: justify;
            -ms-flex-pack: justify;
            justify-content: space-between;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            padding: 7px 8px;
            margin-top: 20px;
            width: 364px;
            height: 30px;
            background: #fff6e4;
            border-radius: 6px;
            cursor: pointer;

            .introduce-left {
                margin: initial;
                display: -webkit-box;
                display: -ms-flexbox;
                display: flex;
                height: 16px;

                img {
                    width: 16px;
                    height: 16px;
                }

                .ranking-precedence {
                    margin-left: 8.89px;
                    font-family: 'PingFang SC';
                    font-style: normal;
                    font-weight: 400;
                    font-size: 12px;
                    line-height: 16px;
                    color: #ff7f24;
                    height: 16px;
                }

            }

            .introduce-right {
                margin: initial;
                display: flex;

                p {
                    height: 16px;
                    font-family: 'PingFang SC';
                    font-style: normal;
                    font-weight: 400;
                    font-size: 11px;
                    line-height: 16px;
                    color: #ff7f24;
                    margin-right: 2px;
                }

                .introduce-right-logo {
                    -webkit-box-sizing: border-box;
                    box-sizing: border-box;
                    margin-top: -4px;
                    padding-left: 5.53px;

                    img {
                        vertical-align: baseline;
                    }
                }
            }

        }

        .introduce-description {
            font-weight: 400;
            font-size: 13px;
            line-height: 18px;
            color: #61666d;
            margin-top: 8px;
            max-width: 364px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            white-space: normal;
            word-break: break-all;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }

        .introduce-title {
            display: flex;

            .introduce-logo {
                // background-image: url(https://n.sinaimg.cn/97973/crawl/191/w495h496/20190626/234b-hyvnhqr1409704.png);
                width: 75px;
                height: 75px;
                background-size: contain;
                background-position: center;
                background-repeat: no-repeat;
                margin: initial;
                margin-right: 10px;
                border-radius: 14px;
                background-size: cover;
            }

            .introduce-info {
                margin: initial;
                display: flex;
                -webkit-box-orient: vertical;
                -webkit-box-direction: normal;
                -ms-flex-direction: column;
                flex-direction: column;
                -webkit-box-pack: center;
                -ms-flex-pack: center;
                justify-content: center;
                margin-left: 5px;

                .download-game-category {
                    margin-bottom: 7px;
                    max-height: 65px;
                    overflow: hidden;
                    margin-left: 0;
                    .tag_list {
                        font-size: 10px;
                        color: #999;
                        text-align: left;
                        line-height: 2.3;
                        //margin-top: 10px;
                        .tag {
                            display: inline-block;
                            border: 1px solid #1281d2;
                            color: #1281d2;
                            padding-left: 4px;
                            padding-right: 4px;
                            border-radius: 5px;
                            margin-left: 5px;
                            line-height: 20px;
                            height: 20px;
                            position: relative;
                        }
                        .tag:first-child{
                            margin-left: 0;
                        }
                        //.tag:before {
                        //    content: "";
                        //    display: block;
                        //    position: absolute;
                        //    width: 15px;
                        //    height: 15px;
                        //    border-left: 1px solid #1281d2;
                        //    border-bottom: 1px solid #1281d2;
                        //    top: 50%;
                        //    -webkit-transform: translateY(-50%) rotate(50deg) skew(10deg);
                        //    -ms-transform: translateY(-50%) rotate(50deg) skew(10deg);
                        //    transform: translateY(-50%) rotate(50deg) skew(10deg);
                        //    left: -8px;
                        //}
                    }
                }

                .introduce-name {
                    line-height: 22px;
                    color: #212121;
                    max-width: 160px;
                    font-family: 'PingFang SC';
                    font-style: normal;
                    font-weight: 700;
                    font-size: 16px;
                    margin: initial;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .score {
                    font-size: 13px;
                    margin: initial;
                    margin-bottom: 10px;
                    //margin-left: -4px;
                    margin-top: 5px;
                    color: #ffa726 !important;
                    display: flex;
                    align-items: center;
                    .average_score{
                        margin-left: 10px
                    }
                    p{
                        width: 160px;
                        overflow: hidden;
                        margin-left: 0;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        font-size: 13px;
                    }
                }

                .count-text {
                    color: #61666d;
                    font-weight: 400;
                    font-size: 13px;
                    line-height: 18px;
                    margin-right: 5px;
                }
            }
        }
    }

    .game-download {
      margin: 0;
      display: flex;
      //width: 200px;
        //text-align: center;
        margin-top: 5px;

        .start-game {
          margin-left:0px;
          font-size: 16px;
          padding:6px 10px;
          //height: 160px;
          background-color: #00aeec;
          color: #fff;
          border: transparent;
          display: inline-block;
          cursor: pointer;
          text-align: center;
          border-radius: 6px;
        }

        .start-game:hover {
            background-color: rgba(#00aeec, .7);
        }

        .end-game{
            margin-left:0px;
            font-size: 16px;
            padding:6px 10px;
            //height: 160px;
            background-color: #a2a2a2;
            color: #fff;
            border: transparent;
            display: inline-block;
            text-align: center;
            border-radius: 6px;
        }
        .end2{
            width: 100%;
        }
    }
}
</style>